<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import type { DrawerProps } from 'ant-design-vue';
import { search, release } from '../api/index';
const placement = ref<DrawerProps['placement']>('right');
const open = ref<boolean>(false);
const env = ref<'gray'|'online'>('gray');
type fileItem = {
  originFile: string,
  sourceFile: string
  desc: string
  message: string
}
const fileList = reactive<fileItem[]>([
  {
    originFile: '',
    sourceFile: '',
    desc: '',
    message: ''
  }
])

const messageAction = (content: string, type: 'success'|'error'|'info'|'warning'|'loading'|'warn' = 'success') => {
  message[type]({
    content: () => content
  });
}

/**
 * 添加资源项
 */
const addFileItem = () => {
  fileList.push({
    originFile: '',
    sourceFile: '',
    desc: '',
    message: ''
  })
}

const showDrawer = () => {
  open.value = true;
};

const onClose = () => {
  open.value = false;
};

let handlerIndex = 0;

/**
 * 更新数组项message提示
 * @param message 
 * @param index 
 */
const updateFileListMessage = (message: string, index: number) => {
  var itemTemp = fileList[index];
  itemTemp.message = message;
  fileList.splice(index, 1, {...itemTemp});
}

/**
 * 递归执行文件替换操作
 */
const runing = () => {
  handlerIndex += 1;
  if (handlerIndex > fileList.length -1) {
    return;
  }
  // 先找到当前文件名
  let originFile = fileList[handlerIndex] && fileList[handlerIndex].originFile;
  let sourceFile = fileList[handlerIndex] && fileList[handlerIndex].sourceFile;
  let desc = fileList[handlerIndex] && fileList[handlerIndex].desc;
  let nowEnv = env.value;
  messageAction(`当前正在执行第${handlerIndex}项${nowEnv}环境替换操作,总共有${fileList.length}项`)
  if (!originFile || !sourceFile) {
    updateFileListMessage('失败：表单内容为空', handlerIndex);
    runing();
    return;
  }
  // 找到待替换的灰度or线上文件
  search(originFile).then((res: any) => {
    const searchFiles = res.data;
    if (!searchFiles || searchFiles.length === 0) {
      // messageAction(`${nowEnv}环境未找到有${originFile}`, 'error');
      updateFileListMessage(`失败：${nowEnv}环境未找到有${originFile}`, handlerIndex);
      runing();
      return;
    }
    let originFileItem = searchFiles.find((item: any) => {
      return item.env === nowEnv && item.value.indexOf(originFile) != -1;
    });
    if (!originFileItem) {
      // messageAction(`${nowEnv}环境未找到有${originFile}`, 'error');
      updateFileListMessage(`失败：${nowEnv}环境未找到有${originFile}`, handlerIndex);
      runing();
      return;
    }
    release({
      configList: [
        {
          key: originFileItem.key,
          value: originFileItem.value.replace(originFile, sourceFile),
          desc: null,
          url: null
        }
      ],
      desc: desc,
      projectId: originFileItem.projectId + ''
    }).then((res:{
      code: number
      data: any
      msg: string | null
    }) => {
      if (res.code === 0){
        // messageAction(`${nowEnv}环境的${originFile}文件成功替换成${sourceFile}`);
        updateFileListMessage(`成功：${nowEnv}环境的${originFile}文件成功替换成${sourceFile}`, handlerIndex);
      } else {
        // messageAction(`${nowEnv}环境的${originFile}文件替换成${sourceFile}失败`, 'error');
        updateFileListMessage(`失败：${nowEnv}环境的${originFile}文件替换成${sourceFile}失败`, handlerIndex);
      }
      runing();
    })
  })
} 

const onSubmit = () => {
  handlerIndex = -1;
  runing();
}

const onReset = () => {
  fileList.splice(0, fileList.length, {
    originFile: '',
    sourceFile: '',
    desc: '',
    message: ''
  });
}

onMounted(() => {

})

defineExpose({
  showDrawer
})
</script>

<template>
  <a-drawer :rootStyle="{zIndex: 10000}" :width="500" title="快捷替换" :placement="placement" :open="open" @close="onClose">
    <template #extra>
      <a-button style="margin-right: 8px" @click="onReset">重置</a-button>
      <a-button type="primary" @click="onSubmit">替换</a-button>
    </template>
    <a-space direction="vertical" style="width: 100%">
      <a-radio-group v-model:value="env">
        <a-radio-button value="gray">灰度</a-radio-button>
        <a-radio-button value="online">正式</a-radio-button>
      </a-radio-group>
      <a-card v-for="(fileItem, index) in fileList" :key="index">
        <a-input placeholder="待替换文件原始文件" v-model:value="fileItem.originFile"  />
        <a-input placeholder="待替换文件新文件" v-model:value="fileItem.sourceFile"  />
        <a-input placeholder="替换描述" v-model:value="fileItem.desc"  />
        <a-alert v-if="fileItem.message" :message="fileItem.message" :type="fileItem.message.indexOf('成功：') !== -1 ? 'success' : 'error'" show-icon />
      </a-card>
      <div class="add-file-wrap">
        <a href="javascript:void(0);" class="add-file" @click="addFileItem">
          <svg t="1693380514716" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2346" width="200" height="200"><path d="M512 42.666667c259.2 0 469.333333 210.133333 469.333333 469.333333s-210.133333 469.333333-469.333333 469.333333S42.666667 771.2 42.666667 512 252.8 42.666667 512 42.666667z m0 64C288.149333 106.666667 106.666667 288.149333 106.666667 512s181.482667 405.333333 405.333333 405.333333 405.333333-181.482667 405.333333-405.333333S735.850667 106.666667 512 106.666667z m34.133333 213.333333c4.693333 0 8.533333 3.84 8.533334 8.533333V469.333333h140.8c4.693333 0 8.533333 3.84 8.533333 8.533334v46.933333a8.533333 8.533333 0 0 1-8.533333 8.533333H554.666667v140.8a8.533333 8.533333 0 0 1-8.533334 8.533334h-46.933333a8.533333 8.533333 0 0 1-8.533333-8.533334V533.333333h-140.8a8.533333 8.533333 0 0 1-8.533334-8.533333v-46.933333c0-4.693333 3.84-8.533333 8.533334-8.533334H490.666667v-140.8c0-4.693333 3.84-8.533333 8.533333-8.533333h46.933333z" fill="currentColor" p-id="2347"></path></svg>
        </a>
      </div>
    </a-space>
  </a-drawer>
</template>

<style scoped>
.add-file{
  width: 50px;
  height: 50px;
  display: block;
  color: #666;
}
.add-file svg{
  width: 100%;
  height: 100%;
}
.add-file:hover{
  color: green;
}
.add-file-wrap{
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
}
</style>
